package com.wzy.oa_sys.service.impl.notice;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzy.oa_sys.mapper.notice.NoticeMapper;
import com.wzy.oa_sys.mapper.user.DeptMapper;
import com.wzy.oa_sys.mapper.user.UserMapper;
import com.wzy.oa_sys.model.pojo.notice.OaNotice;
import com.wzy.oa_sys.model.pojo.user.OaUser;
import com.wzy.oa_sys.model.request.notice.NoticeReq;
import com.wzy.oa_sys.model.response.attendance.VacationResp;
import com.wzy.oa_sys.model.response.notice.NoticeResp;
import com.wzy.oa_sys.service.notice.NoticeService;
import com.wzy.oa_sys.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, OaNotice> implements NoticeService {

    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public List<NoticeResp> getNoticeList(Long userId) {
        List<OaNotice> allNotice = noticeMapper.selectList(null);
        allNotice.sort(Comparator.comparing(OaNotice::getNState));
        List<NoticeResp> noticeRespList = new ArrayList<>();
        allNotice.forEach(notice -> {
            NoticeResp build = NoticeResp.builder()
                    .id(notice.getNNoticeId())
                    .type(notice.getCType())
                    .title(notice.getCTitle())
                    .desc(notice.getCDesc())
                    .releasetime(notice.getDtReleaseTime())
                    .releaseperson(userMapper.selectUserById(notice.getNUserId()).getCRealName())
                    .userId(notice.getNUserId())
                    .examine(notice.getCExamine())
                    .linkId(notice.getNLinkId())
                    .linkType(notice.getCLinkType())
                    .build();
            if(notice.getNDeptId() == 0){
                build.setDept("全部门");
            }else{
                build.setDept(deptMapper.selectDeptById(notice.getNDeptId()).getCDeptName());
            }
            if(notice.getNState() == 3){
                build.setState("一般");
            }else if(notice.getNState() == 2){
                build.setState("重要");
            }else if(notice.getNState() == 1){
                build.setState("紧急");
            }
            if(notice.getNReviewerId()!=0){
                if(userMapper.selectUserById(notice.getNReviewerId())!=null){
                    build.setReviewer(userMapper.selectUserById(notice.getNReviewerId()).getCRealName());
                }
            }
            if(notice.getCExReason()!=null){
                build.setExReason(notice.getCExReason());
            }else{
                build.setExReason("无原因");
            }
            if(notice.getCExamine()!=null){
                if(notice.getCExamine().equals("0")){
                    build.setExamine("待审核");
                }else if(notice.getCExamine().equals("1")){
                    build.setExamine("审核通过");
                }else if(notice.getCExamine().equals("2")){
                    build.setExamine("审核未通过");
                }
            }
            String s = notice.getCRecipient();
            if (!s.equals("[]")) {
                String[] numbers = s.replaceAll("[\\[\\]\\s]", "").split(",");
                int[] result = Arrays.stream(numbers)
                        .mapToInt(Integer::parseInt)
                        .toArray();
                StringBuilder sb = new StringBuilder();
                for (int receiver : result) {
                    if(userMapper.selectUserById(receiver)!=null){
                        sb.append(userMapper.selectUserById(receiver).getCRealName()).append(",");
                    }
                }
                build.setRecipient(sb.toString().substring(0, sb.length() - 1));
            }else{
                build.setRecipient("所有人");
            }
            String s1 = notice.getCRead();
            if (!s1.equals("[]")) {
                String[] numbers2 = s1.replaceAll("[\\[\\]\\s]", "").split(",");
                int[] result2 = Arrays.stream(numbers2)
                        .mapToInt(Integer::parseInt)
                        .toArray();
                for (int receiver : result2) {
                    if(receiver==userId){
                        build.setRead(true);
                        break;
                    }
                }
            }else{
                build.setRead(false);
            }
            noticeRespList.add(build);
        });
        return noticeRespList;
    }


    @Override
    public List<NoticeResp> getMyNoticeList(Long userId,String role) {
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_user_id", userId);
        OaUser oaUser = userMapper.selectOne(queryWrapper);
        List<OaNotice> noticeList = noticeMapper.selectList(null);
        //超级管理员可以查看所有通过的notice
        if(role.contains("SUPERMAN")){
            List<NoticeResp> collect = getNoticeList(userId).stream().filter(notice -> notice.getExamine().equals("审核通过"))
                    .filter(notice -> notice.getReleasetime().isBefore(LocalDateTime.now()))
                    .sorted((n1, n2) -> n2.getReleasetime().compareTo(n1.getReleasetime())) // 根据 releasetime 倒序排序
                    .collect(Collectors.toList());
            return collect;
        }
        //非超级管理员只能查看自己为接收人的notice
        List<NoticeResp> myNoticeList = new ArrayList<>();
        noticeList.forEach(notice->{
            //deptid = 0表示发所有部门下的所有人或者部门id为自己且接收人为空表示发给自己
            if(notice.getNDeptId() == 0||
                    (notice.getNDeptId() == oaUser.getNDeptId()&&notice.getCRecipient().equals("[]"))){
                NoticeResp build = NoticeResp.builder()
                        .id(notice.getNNoticeId())
                        .type(notice.getCType())
                        .title(notice.getCTitle())
                        .releasetime(notice.getDtReleaseTime())
                        .releaseperson(userMapper.selectUserById(notice.getNUserId()).getCRealName())
                        .userId(notice.getNUserId())
                        .examine(notice.getCExamine())
                        .linkId(notice.getNLinkId())
                        .linkType(notice.getCLinkType())
                        .build();
                if(notice.getNDeptId() == 0){
                    build.setDept("全部门");
                }else{
                    build.setDept(deptMapper.selectDeptById(notice.getNDeptId()).getCDeptName());
                }
                if(notice.getNState() == 3){
                    build.setState("一般");
                }else if(notice.getNState() == 2){
                    build.setState("重要");
                }else if(notice.getNState() == 1){
                    build.setState("紧急");
                }
                String s = notice.getCRecipient();
                if (!s.equals("[]")) {
                    String[] numbers2 = s.replaceAll("[\\[\\]\\s]", "").split(",");
                    int[] result2 = Arrays.stream(numbers2)
                            .mapToInt(Integer::parseInt)
                            .toArray();
                    StringBuilder sb = new StringBuilder();
                    for (int receiver : result2) {
                        sb.append(userMapper.selectUserById(receiver).getCRealName()).append(",");
                    }
                    build.setRecipient(sb.toString().substring(0, sb.length() - 1));
                }else{
                    build.setRecipient("所有人");
                }
                //是否已读
                String s1 = notice.getCRead();
                if (!s1.equals("[]")) {
                    String[] numbers2 = s1.replaceAll("[\\[\\]\\s]", "").split(",");
                    int[] result2 = Arrays.stream(numbers2)
                            .mapToInt(Integer::parseInt)
                            .toArray();
                    for (int receiver : result2) {
                        if(receiver==userId){
                            build.setRead(true);
                            break;
                        }
                    }
                }else{
                    build.setRead(false);
                }
                myNoticeList.add(build);

                //deptid不为0且接收人不为空，则只保留接收人包含自己
            }else if(notice.getNDeptId() == oaUser.getNDeptId()&&!notice.getCRecipient().equals("[]")){
                String[] numbers = notice.getCRecipient().replaceAll("[\\[\\]\\s]", "").split(",");
                int[] result = Arrays.stream(numbers)
                        .mapToInt(Integer::parseInt)
                        .toArray();
                //遍历接收人，如果当前用户在接收人中，则添加到返回列表中
                for(int i:result){
                    if(i == userId){
                        NoticeResp build = NoticeResp.builder()
                                .id(notice.getNNoticeId())
                                .type(notice.getCType())
                                .title(notice.getCTitle())
                                .releasetime(notice.getDtReleaseTime())
                                .releaseperson(userMapper.selectUserById(notice.getNUserId()).getCRealName())
                                .examine(notice.getCExamine())
                                .linkId(notice.getNLinkId())
                                .linkType(notice.getCLinkType())
                                .build();
                        if(notice.getNDeptId() == 0){
                            build.setDept("全部门");
                        }else{
                            build.setDept(deptMapper.selectDeptById(notice.getNDeptId()).getCDeptName());
                        }
                        if(notice.getNState() == 3){
                            build.setState("一般");
                        }else if(notice.getNState() == 2){
                            build.setState("重要");
                        }else if(notice.getNState() == 1){
                            build.setState("紧急");
                        }
                        String s = notice.getCRecipient();
                        if (!s.equals("[]")) {
                            String[] numbers1 = s.replaceAll("[\\[\\]\\s]", "").split(",");
                            int[] result1 = Arrays.stream(numbers1)
                                    .mapToInt(Integer::parseInt)
                                    .toArray();
                            StringBuilder sb = new StringBuilder();
                            for (int receiver : result1) {
                                sb.append(userMapper.selectUserById(receiver).getCRealName()).append(",");
                            }
                            build.setRecipient(sb.toString().substring(0, sb.length() - 1));
                        }else{
                            build.setRecipient("所有人");
                        }
                        //是否已读
                        String s1 = notice.getCRead();
                        if (!s1.equals("[]")) {
                            String[] numbers2 = s1.replaceAll("[\\[\\]\\s]", "").split(",");
                            int[] result2 = Arrays.stream(numbers2)
                                    .mapToInt(Integer::parseInt)
                                    .toArray();
                            for (int receiver : result2) {
                                if(receiver==userId){
                                    build.setRead(true);
                                    break;
                                }
                            }
                        }else{
                            build.setRead(false);
                        }
                        myNoticeList.add(build);
                        break;
                    }
                }
            }
        });
        return myNoticeList.stream()
                .filter(notice -> "1".equals(notice.getExamine())) // 过滤 examine 为 "1" 的通知
                .filter(notice -> notice.getReleasetime().isBefore(LocalDateTime.now())) // 过滤 releasetime 在当前时间之前的通知
                .sorted((n1, n2) -> n2.getReleasetime().compareTo(n1.getReleasetime())) // 根据 releasetime 倒序排序
                .collect(Collectors.toList());
    }

    @Override
    public List<NoticeResp> getSomeNotices(Long userId, String s) {
        List<NoticeResp> myNoticeList = getMyNoticeList(userId, s);
        if(myNoticeList.size() >7){
            myNoticeList = myNoticeList.subList(0,7);
        }
        return myNoticeList;
    }

    public List<NoticeResp> getNeedAttNoticeList() {
        List<OaNotice> allNotice = noticeMapper.selectList(null);
        allNotice.sort(Comparator.comparing(OaNotice::getNState));
        List<NoticeResp> noticeRespList = new ArrayList<>();
        allNotice.forEach(notice -> {
            if(notice.getCExamine().equals("0")){
            NoticeResp build = NoticeResp.builder()
                    .id(notice.getNNoticeId())
                    .type(notice.getCType())
                    .title(notice.getCTitle())
                    .desc(notice.getCDesc())
                    .releasetime(notice.getDtReleaseTime())
                    .releaseperson(userMapper.selectUserById(notice.getNUserId()).getCRealName())
                    .userId(notice.getNUserId())
                    .examine("待审核")
                    .build();
            if(notice.getNDeptId() == 0){
                build.setDept("全部门");
            }else{
                build.setDept(deptMapper.selectDeptById(notice.getNDeptId()).getCDeptName());
            }
            if(notice.getNState() == 3){
                build.setState("一般");
            }else if(notice.getNState() == 2){
                build.setState("重要");
            }else if(notice.getNState() == 1){
                build.setState("紧急");
            }
            String s = notice.getCRecipient();
            if (!s.equals("[]")) {
                String[] numbers = s.replaceAll("[\\[\\]\\s]", "").split(",");
                int[] result = Arrays.stream(numbers)
                        .mapToInt(Integer::parseInt)
                        .toArray();
                StringBuilder sb = new StringBuilder();
                for (int receiver : result) {
                    sb.append(userMapper.selectUserById(receiver).getCRealName()).append(",");
                }
                build.setRecipient(sb.toString().substring(0, sb.length() - 1));
            }else{
                build.setRecipient("所有人");
            }
            noticeRespList.add(build);
            }
        });
        return noticeRespList;
    }

    @Override
    public List<NoticeResp> getICanApprovedNotices(Long userId) {
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_user_id", userId);
        OaUser oaUser = userMapper.selectOne(queryWrapper);

        List<NoticeResp> noticeRespList = getNeedAttNoticeList();

        // 判断角色并进行相应的过滤
        if (oaUser.getNRole() == 1) {
            return noticeRespList; // 角色为1，返回全部请假列表
        } else if (oaUser.getNRole() == 2) {
            // 角色为2，仅保留 reviewId 等于 userId 的数据
            return noticeRespList.stream()
                    .filter(notice -> notice.getReviewerId() == userId) // 过滤
                    .collect(Collectors.toList()); // 收集结果为列表
        }

        return noticeRespList; // 默认返回（可能是为了编译的安全）
    }

    @Override
    public void updateTheNotice(NoticeReq noticeReq,HttpServletRequest request) {
        Long userId = jwtUtil.extractUserId(request);
        System.out.println(noticeReq);
        QueryWrapper<OaNotice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_notice_id", noticeReq.getId());
        OaNotice oaNotice = noticeMapper.selectOne(queryWrapper);
        if(oaNotice != null){
            oaNotice.setCExamine(noticeReq.getExamine());
            oaNotice.setCExReason(noticeReq.getExReason());
            //公告审核后发布通知
            NoticeReq noticeReq1 = new NoticeReq();
            noticeReq1.setType("更新");
            noticeReq1.setState(2);
            noticeReq1.setTitle("公告审核结果通知");
            noticeReq1.setDesc("您有一条公告审核结果通知，请注意查看。可点击链接查看具体信息。");
            noticeReq1.setReleasetime(LocalDateTime.now().minusHours(8));
            //请假人信息
            noticeReq1.setDeptname(oaNotice.getNDeptId());
            String s = oaNotice.getCRecipient();
            ArrayList<Long> cRecipient = new ArrayList<>();
            if (!s.equals("[]")) {
                String[] numbers = s.replaceAll("[\\[\\]\\s]", "").split(",");
                int[] result = Arrays.stream(numbers)
                        .mapToInt(Integer::parseInt)
                        .toArray();
                for (int receiver : result) {
                    cRecipient.add(Long.valueOf(receiver));
                }
            }
            noticeReq1.setReceiverList(cRecipient);
            noticeReq1.setReviewer(userId);
            noticeReq1.setExamine("1");
            noticeReq1.setExReason("请假信息审核消息");
            noticeReq1.setLinkId(noticeReq.getId());
            noticeReq1.setLinkType("notice");
            addNotice(noticeReq1,userId);
            noticeMapper.update(oaNotice, queryWrapper);
        }
    }



    @Override
    public void addNotice(NoticeReq noticeReq,Long userId) {
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_user_id", userId);
        OaUser oaUser = userMapper.selectOne(queryWrapper);
        OaNotice oaNotice = new OaNotice();
        oaNotice.setCExamine("0");
        //超级管理员直接审核通过
        if(oaUser != null){
            if(oaUser.getNRole() == 1){
                oaNotice.setCExamine("1");
                oaNotice.setCExReason("超级管理员直接审核通过");
            }
        }
        oaNotice.setCType(noticeReq.getType());
        oaNotice.setCTitle(noticeReq.getTitle());
        oaNotice.setNState(noticeReq.getState());
        oaNotice.setCDesc(noticeReq.getDesc());
        oaNotice.setNUserId(userId);
        oaNotice.setNDeptId(noticeReq.getDeptname());
        LocalDateTime releasetime = noticeReq.getReleasetime();
        oaNotice.setDtReleaseTime(releasetime.plusHours(8));
        if(noticeReq.getReceiverList().size() != 0){
            oaNotice.setCRecipient(noticeReq.getReceiverList().toString());
        }else{
            oaNotice.setCRecipient("[]");
        }
        oaNotice.setNReviewerId(noticeReq.getReviewer());
        oaNotice.setCRead("[]");
        if(noticeReq.getLinkId()!=0){
            oaNotice.setNLinkId(noticeReq.getLinkId());
            oaNotice.setCLinkType(noticeReq.getLinkType());
        }
        noticeMapper.insert(oaNotice);
    }


    //除管理员外审核通过的数据不可修改
    //管理员修改后直接通过否则均变为待审核
    @Override
    public void updateNotice(NoticeReq noticeReq,HttpServletRequest request) {
        Long userId = jwtUtil.extractUserId(request);
        String role = jwtUtil.extractUserRole(request);
        QueryWrapper<OaNotice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_notice_id", noticeReq.getId());
        OaNotice oaNotice = noticeMapper.selectOne(queryWrapper);
        Boolean flag = false;
        //超级管理员直接审核通过
        if(oaNotice != null){
            if(!oaNotice.getCType().equals(noticeReq.getType())){
                oaNotice.setCType(noticeReq.getType());
                flag = true;
            }
            if(!oaNotice.getCTitle().equals(noticeReq.getTitle())){
                flag = true;
                oaNotice.setCTitle(noticeReq.getTitle());
            }
            if(!oaNotice.getCDesc().equals(noticeReq.getDesc())){
                flag = true;
                oaNotice.setCDesc(noticeReq.getDesc());
            }
            if(oaNotice.getNState()!=noticeReq.getState()){
                flag = true;
                oaNotice.setNState(noticeReq.getState());
            }
            if(!oaNotice.getDtReleaseTime().equals(noticeReq.getReleasetime())){
                flag = true;
                oaNotice.setDtReleaseTime(noticeReq.getReleasetime());
            }
            if(noticeReq.getDeptname()!=oaNotice.getNDeptId()){
                flag = true;
                oaNotice.setNDeptId(noticeReq.getDeptname());
            }
            if(!noticeReq.getReceiverList().toString().equals(oaNotice.getCRecipient())){
                flag = true;
                if(noticeReq.getReceiverList().size() != 0){
                    oaNotice.setCRecipient(noticeReq.getReceiverList().toString());
                }else{
                    oaNotice.setCRecipient("[]");
                }
            }
            if(flag){
                if(role.contains("SUPERMAN")&&flag){
                    oaNotice.setCExamine("1");
                }else{
                    oaNotice.setCExamine("0");
                }
                oaNotice.setCRead("[]");
                noticeMapper.update(oaNotice,queryWrapper);
            }else{
                System.out.println("公告数据未修改");
                throw new RuntimeException("公告数据未修改");
            }

        }



    }

    @Override
    public int deleteNoticeById(Integer id) {
        return noticeMapper.deleteNoticeById(id);
    }

    @Override
    public NoticeResp getNoticeDetailById(Integer id) {
        QueryWrapper<OaNotice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_notice_id", id);
        OaNotice oaNotice = noticeMapper.selectOne(queryWrapper);
        if(oaNotice!= null){
            NoticeResp build = NoticeResp.builder()
                    .id(oaNotice.getNNoticeId())
                    .type(oaNotice.getCType())
                    .title(oaNotice.getCTitle())
                    .desc(oaNotice.getCDesc())
                    .releasetime(oaNotice.getDtReleaseTime())
                    .linkId(oaNotice.getNLinkId())
                    .linkType(oaNotice.getCLinkType())
                    .build();
            if(oaNotice.getNReviewerId()!=0){
                if(userMapper.selectUserById(oaNotice.getNReviewerId())!=null){
                    build.setReviewer(userMapper.selectUserById(oaNotice.getNReviewerId()).getCRealName());
                }
            }
            if(oaNotice.getCExReason()!=null){
                build.setExReason(oaNotice.getCExReason());
            }else{
                build.setExReason("无原因");
            }
            if(oaNotice.getCExamine()!=null){
                if(oaNotice.getCExamine().equals("0")){
                    build.setExamine("待审核");
                }else if(oaNotice.getCExamine().equals("1")){
                    build.setExamine("审核通过");
                }else if(oaNotice.getCExamine().equals("2")){
                    build.setExamine("审核未通过");
                }
            }
            if(oaNotice.getNDeptId() == 0){
                build.setDept("全部门");
            }else{
                build.setDept(deptMapper.selectDeptById(oaNotice.getNDeptId()).getCDeptName());
            }
            if(oaNotice.getNState() == 3){
                build.setState("一般");
            }else if(oaNotice.getNState() == 2){
                build.setState("重要");
            }else if(oaNotice.getNState() == 1){
                build.setState("紧急");
            }
            if(oaNotice.getNUserId() != 0){
                build.setReleaseperson(userMapper.selectUserById(oaNotice.getNUserId()).getCRealName());
            }
            if(oaNotice.getNReviewerId()!=0){
                build.setReviewer(userMapper.selectUserById(oaNotice.getNReviewerId()).getCRealName());
            }
            String s = oaNotice.getCRecipient();
            if(s!= null && !s.equals("[]")){
                String[] numbers = s.replaceAll("[\\[\\]\\s]", "").split(",");
                int[] result = Arrays.stream(numbers)
                        .mapToInt(Integer::parseInt)
                        .toArray();
                StringBuilder sb = new StringBuilder();
                for (int receiver : result) {
                    sb.append(userMapper.selectUserById(receiver).getCRealName()).append(",");
                }
                build.setRecipient(sb.toString().substring(0, sb.length() - 1));
            }else{
                build.setRecipient("全体成员");
            }
            return build;
        }
        return null;
    }

    @Override
    public void readNotice(long id, HttpServletRequest request) {
        Long userId = jwtUtil.extractUserId(request);
        QueryWrapper<OaNotice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_notice_id", id);
        OaNotice oaNotice = noticeMapper.selectOne(queryWrapper);
        if(oaNotice!=null){
            //是否已读
            boolean flag = false;
            //是否已读
            String s1 = oaNotice.getCRead();
            if (!s1.equals("[]")) {
                String[] numbers2 = s1.replaceAll("[\\[\\]\\s]", "").split(",");
                int[] result2 = Arrays.stream(numbers2)
                        .mapToInt(Integer::parseInt)
                        .toArray();
                for (int receiver : result2) {
                    if(receiver==userId){
                        flag = true;
                        break;
                    }
                }
            }
            //未读
            if(!flag){
            String cRead = oaNotice.getCRead();
            if(cRead != null && !cRead.equals("[]")){
                cRead = cRead.substring(0, cRead.length() - 1)+","+userId+"]";
                oaNotice.setCRead(cRead);
            }else{
                oaNotice.setCRead("["+userId+"]");
            }
            noticeMapper.update(oaNotice, queryWrapper);
            }
        }
    }


}
